import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 均先生
 * Date: 2023-08-26
 * Time: 20:39
 */
public class BinarySearch {
    //二分查找是建立在有序数组的情况下进行查找
    public static int binarySearch(int[] array,int key) {
        int i = 0;
        int j = array.length - 1;
        while (i <= j) {
            int mid = (i+j) / 2;
            if (array[mid] < key) {
                i = mid + 1;
            }else if (array[mid] == key) {
                return mid;
            }else {
                j = mid - 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr1 = {2,4,6,8,10};
        int[] arr2 = {2,4,6,8};
        System.out.println(binarySearch(arr1,2));
        System.out.println(binarySearch(arr1,6));
        System.out.println(binarySearch(arr1,10));

        System.out.println("============================");

        System.out.println(binarySearch(arr2,2));
        System.out.println(binarySearch(arr2,4));
        System.out.println(binarySearch(arr2,6));
        System.out.println(binarySearch(arr2,8));

        //Arrays类里的二分查找
        System.out.println(Arrays.binarySearch(arr1,10));
    }
}
